package com.opennews.openplatform.myspringbootmvccore.helper;

import com.opennews.openplatform.myspringbootcore.util.SharedUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class HttpRequestHepler {
    private HttpServletRequest request;

    public HttpRequestHepler(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * Gets client request ip address
     *
     * @return
     */
    public String getRequstIpAdress() {
        String LOCALHOST_IPV4 = "127.0.0.1";
        String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
        String unknownStatus = "unknown";

        String ipAddress = request.getHeader("X-Forwarded-For");

        if (SharedUtil.isNullOrEmpty(ipAddress) || unknownStatus.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (SharedUtil.isNullOrEmpty(ipAddress) || unknownStatus.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (SharedUtil.isNullOrEmpty(ipAddress) || unknownStatus.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if (LOCALHOST_IPV4.equals(ipAddress) || LOCALHOST_IPV6.equals(ipAddress)) {
                try {
                    InetAddress inetAddress = InetAddress.getLocalHost();
                    ipAddress = inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }

        if (!SharedUtil.isNullOrEmpty(ipAddress) && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }

        return ipAddress;
    }
}
